const groupbuyModel = require('../models/groupbuyModel');

// 获取拼团状态
exports.getGroupBuyStatus = async (req, res) => {
    try {
        const { productId, userId } = req.query;
        console.log("查询商品ID:", productId, "用户ID:", userId);

        if (!productId || !userId) {
            return res.status(400).json({
                message: '商品ID和用户ID都是必需的'
            });
        }

        // 获取商品当前的拼团状态
        const groupBuyInfo = await groupbuyModel.getGroupBuyStatus(productId);

        if (!groupBuyInfo) {
            return res.json({
                code: 200,
                message: '暂无用户拼单'
            });
        }

        // 获取参与者信息
        const participants = await groupbuyModel.getParticipants(groupBuyInfo.groupbuy_id);

        // 计算剩余名额
        const remaining = groupBuyInfo.group_size - groupBuyInfo.current_count;

        // 检查用户是否是参与者
        const isParticipant = participants.some(p => p.user_id === parseInt(userId));

        res.json({
            code: 200,
            ...groupBuyInfo,
            participants,
            remaining,
            isParticipant
        });
    } catch (error) {
        console.error('获取拼团状态失败:', error);
        res.status(500).json({
            code: 500,
            message: '服务器错误'
        });
    }
};

// 发起拼团
exports.startGroupBuy = async (req, res) => {
    try {
        const { product_id, user_id, end_time } = req.body;

        // 检查是否已存在进行中的拼团
        const existingGroupBuy = await groupbuyModel.getActiveGroupBuy(product_id);
        if (existingGroupBuy) {
            return res.status(400).json({
                message: '该商品已存在进行中的拼团活动'
            });
        }

        // 创建拼团活动
        const groupbuy_id = await groupbuyModel.createGroupBuy({
            product_id,
            creator_user_id: user_id,
            end_time
        });

        res.json({
            success: true,
            groupbuy_id,
            message: '拼团活动创建成功'
        });
    } catch (error) {
        console.error('创建拼团失败:', error);
        res.status(500).json({ message: '服务器错误' });
    }
};

// 加入拼团
exports.joinGroupBuy = async (req, res) => {
    try {
        const { groupbuy_id, user_id } = req.body;

        // 检查拼团是否存在且进行中
        const groupBuy = await groupbuyModel.getGroupBuyById(groupbuy_id);
        if (!groupBuy || groupBuy.status !== 'in_progress') {
            return res.status(400).json({
                message: '拼团活动不存在或已结束'
            });
        }

        // 检查是否已参与
        const isParticipant = await groupbuyModel.isParticipant(groupbuy_id, user_id);
        if (isParticipant) {
            return res.status(400).json({
                message: '您已参与该拼团'
            });
        }

        // 检查是否还有剩余名额
        if (groupBuy.current_count >= groupBuy.group_size) {
            return res.status(400).json({
                message: '拼团人数已满'
            });
        }

        // 加入拼团
        await groupbuyModel.joinGroupBuy(groupbuy_id, user_id);

        // 更新拼团状态
        const newCount = groupBuy.current_count + 1;
        if (newCount >= groupBuy.group_size) {
            await groupbuyModel.updateGroupBuyStatus(groupbuy_id, 'completed');
        }

        res.json({
            success: true,
            message: '成功加入拼团'
        });
    } catch (error) {
        console.error('加入拼团失败:', error);
        res.status(500).json({ message: '服务器错误' });
    }
};

// 获取拼团详情
exports.getGroupBuyDetail = async (req, res) => {


    try {
        const { productId } = req.body;
        console.log("查询商品ID:", productId);

        const groupBuy = await groupbuyModel.getGroupBuyById(productId);
        if (!groupBuy) {
            return res.json({
                code: 200,
                message: '暂无用户拼单'
            });
        }
        console.log(groupBuy);


        // 获取参与者信息
        // const participants = await groupbuyModel.getParticipants(groupBuy.groupbuy_id);

        res.json({
            code: 200,
            data: groupBuy
        });
    } catch (error) {
        console.error('获取拼团详情失败:', error);
        res.status(500).json({
            code: 500,
            message: '服务器错误'
        });
    }
}; 